<template >
  <view class="fuel_station_wraper">
    <!-- <view class="fuel_title">
      优选站点
    </view> -->
    <view class="other_fuel">
      <view class="fuel_container" v-for="(item, index) in fuelList" :key="item.stationId">
        <view class="header_wraper" @click="goOfficial(item)">
          <view class="left">
            <view class="header_avatar">
              <img
                :src="item.headImg"
                alt=""
                v-if="!!item.headImg"
              />
              <open-data v-else type="userAvatarUrl"></open-data>
            </view>
            <view class="header_name">
              <view class="title">
                {{ item.stationName }}
              </view>
              <view class="main_title_wraper">
                <view class="main_title" v-if="selectStaOilGunList[index].oilStationPrice">
                  <text class="text">￥</text>{{getDescentPrice(selectStaOilGunList[index].oilStationPrice)}}
                </view>
                <!-- <view class="descent_price_wrap">
                  <view class="descent_icon"></view>
                  <view class="descent_price">直降 <text class="descent_text">{{descentPrice}}</text> </view>
                </view> -->
              </view>
              <!-- <view class="main_card">
                <view class="main_station">枪价 ￥{{selectStaOilGunList[index].oilStationPrice || ''}}</view>
                <view class="main_station">国标价 ￥{{selectStaOilGunList[index].oilOfficialPrice || ''}}</view>
              </view> -->
            </view>
            <!-- <view class="header_tuijian">推荐</view> -->
          </view>
        </view>
        <view class="divider_line"></view>
        <view class="bottom_button">
          <view class="fixed_wraper" @click="goOfficial(item)">
            <view class="fixed_top">
              <view class="icon_fixed"></view>
              <view class="distance">距我{{getDistances(item.stationLatitude, item.stationLongitude)}}</view>
            </view>
            <view class="info">
              {{item.detailRegionData}}
            </view>
          </view>
          <view class="item" @click="openLocation(item)">
            <uni-icons type="paperplane-filled" color="#fc6703" size="30"></uni-icons>
            <!-- <view class="icon nav"></view> -->
          </view>
        </view>
      </view>
      <view class="none_more">没有更多了</view>
    </view>
  </view>
</template>

<script>
  import {mapMutations} from "vuex";
export default {
  head() {
    return {
      title: "选择油站",
    };
  },
  // props: ['enterpriseId'],
  data() {
    return {
      fuelList: [],
      latitude: 0, // 纬度
      longitude: 0, // 经度
      descentPrice: '0.40', // 直降价格
      appletShowOilNamePrice: '', // 展示油号
    };
  },
  created() {
    this.init();
  },
  computed: {
    // 展示的油站信息
    selectStaOilGunList() {
      return this.fuelList.map(item => {
        if (item.oilList) {
          const obj = item.oilList.find(val => val.oilName === this.appletShowOilNamePrice) || {};
          return obj;
        }
        return item;
      }) || [];
    }
  },
  // watch:{
  //   enterpriseId(newval,oldval){
  //     if (this.enterpriseId) {
  //       this.init()
  //     }
  //   }
  // },
  methods: {
    ...mapMutations({
      updateEnterpriseId: "updateEnterpriseId"
    }),
    async init() {
      const that = this;
			uni.getLocation({
				type: 'wgs84',
				success: function (res) {
					console.log(res, '获取定位成功');
					that.latitude = res.latitude; //纬度，浮点数，范围为90 ~ -90
          that.longitude = res.longitude; //经度，浮点数，范围为180 ~ -180。
				},
				fail: function (res) {
					console.log(res, 'eee');
					uni.showModal({
							title: '您未开启手机地理位置',
							content: '小程序将无法正常使用',
							success: (res) => {
									if (res.confirm) {
											uni.openSetting()
									}
							}
					})
				}
			});
      try {
        const res = await this.$Request({
          url: "/appletSelectStationList",
          method: "GET",
          data: {enterpriseId: this.enterpriseId}
        });
        if(res.retCode !== 0) {
          throw new Error("获取油站失败")
        }
        this.fuelList = res.data.stationList || [];
        if (res.data.stationList && res.data.stationList.length === 1) {
          this.goOfficial()
        }
        this.appletShowOilNamePrice = res.data.appletShowOilNamePrice || '92#';
      } catch (error) {
        uni.showToast({
          title: error,
          icon: "error"
        });
      }
    },

    getDescentPrice(val) {
      return Number((Number(val) - Number(this.descentPrice)).toFixed(2));
    },

    goOfficial(val) {
      if (!this.phoneNumber) {
        uni.showToast({
          title: '请授权登录',
          icon: "error"
        })
        return;
      }
      let item = val;
      if (!val) {
        item = this.fuelList[0];
        if (!item) {
          uni.showToast({
            title: '当前没有可用油站',
            icon: "error"
          })
          return;
        }
      }
      uni.setStorageSync('stationData', JSON.stringify({appletShowOilNamePrice: this.appletShowOilNamePrice, ...item}));
      const distances = this.getDistances(item.stationLatitude, item.stationLongitude);
      uni.navigateTo({
        url: `/subPack/fuel/remit?stationId=${item.stationId}&stationName=${item.stationName}&distances=${distances}`,
      })
    },

    openLocation(item) {
      let longitude = Number(item.stationLongitude).toFixed(0);
      let latitude = Number(item.stationLatitude).toFixed(0);
      if (Number(latitude) > 90 || Number(latitude) < -90) {
        latitude = '0'
      }
      if (Number(longitude) > 180 || Number(longitude) < -180) {
        longitude = '0'
      }
      console.log(item, longitude, latitude, 'latitude');
      uni.openLocation({
        longitude: Number(longitude),
        latitude: Number(latitude),
        name: item.stationName,
        success: function () {
          console.log('success');
        },
        fail: function (e) {
          console.log(e, 'fail');
        }
      })
    },

    rad(d) {
      return d * Math.PI / 180.0;
    },

    getDistances(lat2, lng2) {
      let radLat1 = this.rad(this.latitude);
      let radLat2 = this.rad(Number(lat2));
      let a = radLat1 - radLat2;
      let b = this.rad(this.longitude) - this.rad(Number(lng2));
      let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
          Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
      s = s * 6378.137;
      // 输出为公里
      s = Math.round(s * 10000) / 10000;

      let distance = s;
      let distance_str = "";

      if (parseInt(distance) >= 1) {
          // distance_str = distance.toFixed(1) + "km";
          distance_str = distance.toFixed(2) + "km";
      } else {
          // distance_str = distance * 1000 + "m";
          distance_str = (distance * 1000).toFixed(2) + "m";
      }

      return distance_str;
    }
  },
};
</script>

<style lang="scss" >
  .fuel_station_wraper {
    box-sizing: border-box;
    padding: 20rpx 0 200rpx;
    min-height: 100vh;
    background: #f5f5f5;
    .fuel_title {
      margin: 0rpx 0 30rpx 20rpx;
      line-height: 64rpx;
      color: #000;
      font-size: 34rpx;
      font-family: 'microsoft-yahei';
      font-weight: 900;
    }
    .other_fuel {
      display: flex;
      flex-direction: column;
      width: 100%;
      .fuel_container {
        margin-bottom: 10rpx;
        padding-top: 30rpx;
        border-radius: 20rpx;
        background-color: #fff;
        overflow: hidden;

        .header_wraper {
          display: flex;
          justify-content: space-between;
          padding: 0 32rpx;
          .left {
            display: flex;
            position: relative;
            width: 100%;
            .header_avatar {
              width: 100rpx;
              height: 100rpx;
              margin: 20rpx;
              img {
                width: 100%;
                height: 100%;
              }
            }
            .header_name {
              display: flex;
              flex-direction: column;
              margin-left: 40rpx;
              .main_card {
                display: flex;
                align-items: center;
                margin: 12rpx 0 12rpx;
                .main_station {
                  text-decoration: line-through;
                  font-size: 22rpx;
                  color: #999;
                  height: 40rpx;
                  margin-top: 10rpx;
                  margin-right: 10rpx;
                }
              }
              .title {
                font-size: 34rpx;
                max-width: 700rpx;
                font-weight: 900;
                color: #000;
                margin-bottom: 12rpx;
              }
              .main_title_wraper {
                display: flex;
                .descent_price_wrap {
                  display: flex;
                  align-items: center;
                  border: 1px solid #deb183;
                  background-color: #fdfefe;
                  border-radius: 10rpx;
                  padding: 0rpx 6rpx;
                  margin-top: 16rpx;
                  height: 36rpx;
                  .descent_icon {
                    width: 32rpx;
                    height: 32rpx;
                    background: url("../static/fuel/xiajiang.png") no-repeat 0 0;
                    background-size: 100% 100%;
                  }
                  .descent_price {
                    color: #d79670;
                    font-size: 24rpx;
                    font-weight: 400;
                    .descent_text {
                      font-weight: 600;
                    }
                  }
                }
                .main_title {
                  font-size: 46rpx;
                  font-weight: 600;
                  margin-right: 20rpx;
                  .text {
                    font-size: 28rpx;
                  }
                }
              }
            }
            .header_tuijian {
              position: absolute;
              border-radius: 10rpx;
              right: 0;
              top: 0;
              font-size: 24rpx;
              padding: 4rpx 12rpx;
              height: 32rpx;
              background-color: #f64601;
              color: #fff;
            }
          }
        }


        .divider_line {
          width: 100%;
          height: 1px;
          background-color: #F5F5F5;
        }
        .bottom_button {
          display: flex;
          .fixed_wraper {
            position: relative;
            display: flex;
            flex-direction: column;
            justify-content: center;
            width: 80%;
            margin-left: 30rpx;
            &::after {
              content: '';
              position: absolute;
              width: 1px;
              height: 80rpx;
              background-color: #f5f5f5;
              right: 0;
            }
            .fixed_top {
              display: flex;
              margin-bottom: 16rpx;
              .distance {
                font-size: 24rpx;
                font-weight: 600;
              }
              .icon_fixed {
                width: 32rpx;
                height: 32rpx;
                background: url("../static/fuel/fixed.png") no-repeat 0 0;
                background-size: 100% 100%;
              }
            }
            .info {
              max-width: 500rpx;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
              font-size: 22rpx;
              color: #999;
            }
          }
          .item {
            padding: 40rpx;
            .icon {
              width: 40rpx;
              height: 40rpx;
              &.nav {
                background: url("../static/fuel/nav.png") no-repeat 0 0;
                background-size: 100% 100%;
              }
            }
          }
        }
      }
      .none_more {
        color: #333;
        font-weight: 6;
        font-size: 26rpx;
        position: relative;
        width: 100%;
        text-align: center;
        &::after {
          content: '';
          position: absolute;
          width: 46rpx;
          height: 1px;
          background-color: #ccc;
          right: 230rpx;
          top: 20rpx;
        }
        &::before {
          content: '';
          position: absolute;
          width: 46rpx;
          height: 1px;
          background-color: #ccc;
          left: 230rpx;
          top: 20rpx;
        }
      }
    }
  }
</style>
